﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Diagnostics;
using Microsoft.TeamFoundation.Client;
using System.Threading;

namespace TestPlanWordWriter.Common.Word
{
    public class DocumentContentRefresh
    {
        public void RefreshTestRuns(Stream wordOutputStream, TfsTeamProjectCollection tpc, string teamProjectName, TestPlanDocWriterSettings settings, CancellationToken cancelToken)
        {
            throw new NotImplementedException();
        }

        public void RefreshTestPlans(Stream wordOutputStream, TfsTeamProjectCollection tpc, string teamProjectName, TestPlanDocWriterSettings settings, CancellationToken cancelToken)
        {
            using (WordprocessingDocument outDoc = WordprocessingDocument.Open(wordOutputStream, true))
            {
                MainDocumentPart mainPart = outDoc.MainDocumentPart;
                foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>().ToList())
                {
                    Tag contentTag = sdt.Descendants<Tag>().FirstOrDefault();
                    if (contentTag != null)
                    {
                        string tag = contentTag.Val.Value;
                        ContentControlIdentification contentIdentification = new ContentControlIdentification(tag);
                        if (contentIdentification.IsTestPlanControl)
                        {
                            int planId = contentIdentification.PlanIdFromControlTag;
                            TestResultsSettings resultsSettings = contentIdentification.ResultsSettings;

                            TestPlanInfoSimpleBuilder builder = new TestPlanInfoSimpleBuilder(tpc, teamProjectName);
                            TestPlanInfo info = builder.BuildPlanInfo(planId, cancelToken, resultsSettings);

                            SdtBlock controlRun = (SdtBlock)sdt;
                            SdtContentBlock contentRun = controlRun.Descendants<SdtContentBlock>().FirstOrDefault();

                            contentRun.RemoveAllChildren();

                            WordPlanContentBuilder contentBuilder = new WordPlanContentBuilder(settings, contentIdentification);
                            contentBuilder.FillCompositeElementContent(info, contentRun);
                        }
                    }
                }
                mainPart.Document.Save();
            }            
        }
    }
}
